import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

/// SharedPreferences存储服务类，负责应用中的所有本地数据存储操作
class SharedPreferencesService {
  static final SharedPreferencesService _instance = SharedPreferencesService._internal();
  late SharedPreferences _prefs;
  bool _isInitialized = false;

  // 存储键前缀
  static const String _prefix = 'moonmate_';

  // 表名对应的键
  static const String keyUser = '${_prefix}user';
  static const String keyUserSettings = '${_prefix}user_settings';
  static const String keyPeriods = '${_prefix}periods';
  static const String keySymptoms = '${_prefix}symptoms';
  static const String keyBBTRecords = '${_prefix}bbt_records';
  static const String keyCMRecords = '${_prefix}cm_records';
  static const String keyOvulationTests = '${_prefix}ovulation_tests';
  static const String keyIntercourse = '${_prefix}intercourse';
  static const String keyFolicAcid = '${_prefix}folic_acid';
  static const String keyPregnancy = '${_prefix}pregnancy';
  static const String keyBabyInfo = '${_prefix}baby_info';
  static const String keyBabyGrowth = '${_prefix}baby_growth';
  static const String keyKnowledgeArticles = '${_prefix}knowledge_articles';
  static const String keyHealthMetrics = '${_prefix}health_metrics';
  static const String keyPredictionData = '${_prefix}prediction_data';
  static const String keyProgressRecords = '${_prefix}progress_records';
  static const String keyKnowledge = '${_prefix}knowledge';

  /// 工厂构造函数，确保只创建一个实例
  factory SharedPreferencesService() {
    return _instance;
  }
  


  /// 私有构造函数
  SharedPreferencesService._internal();

  /// 初始化SharedPreferences
  Future<void> initialize() async {
    if (!_isInitialized) {
      _prefs = await SharedPreferences.getInstance();
      _isInitialized = true;
    }
  }

  /// 存储单个对象
  Future<bool> setObject(String key, Map<String, dynamic> value) async {
    _checkInitialized();
    try {
      final jsonString = jsonEncode(value);
      return await _prefs.setString(key, jsonString);
    } catch (e) {
      // 移除print语句，返回false表示操作失败
      return false;
    }
  }

  /// 检查是否已初始化
  void _checkInitialized() {
    if (!_isInitialized) {
      throw Exception('SharedPreferencesService not initialized');
    }
  }

  /// 保存单个对象
  Future<bool> saveObject(String key, Map<String, dynamic> data) async {
    _checkInitialized();
    try {
      final jsonString = jsonEncode(data);
      return await _prefs.setString(key, jsonString);
    } catch (e) {
      // 移除print语句，返回false表示操作失败
      return false;
    }
  }

  /// 获取单个对象
  Map<String, dynamic>? getObject(String key) {
    _checkInitialized();
    try {
      final jsonString = _prefs.getString(key);
      if (jsonString == null) return null;
      return jsonDecode(jsonString) as Map<String, dynamic>;
    } catch (e) {
      // 移除print语句，返回null表示获取失败
      return null;
    }
  }

  /// 保存对象列表
  Future<bool> saveObjectList(String key, List<Map<String, dynamic>> dataList) async {
    _checkInitialized();
    try {
      final jsonString = jsonEncode(dataList);
      return await _prefs.setString(key, jsonString);
    } catch (e) {
      // 移除print语句，返回false表示操作失败
      return false;
    }
  }
  
  /// 存储对象列表
  Future<bool> setObjectList(String key, List<Map<String, dynamic>> value) async {
    _checkInitialized();
    try {
      final jsonString = jsonEncode(value);
      return await _prefs.setString(key, jsonString);
    } catch (e) {
      // 移除print语句，返回false表示操作失败
      return false;
    }
  }

  /// 获取对象列表
  List<Map<String, dynamic>> getObjectList(String key) {
    _checkInitialized();
    try {
      final jsonString = _prefs.getString(key);
      if (jsonString == null) return [];
      final List<dynamic> list = jsonDecode(jsonString);
      return list.map((e) => e as Map<String, dynamic>).toList();
    } catch (e) {
      // 移除print语句，返回空列表表示获取失败
      return [];
    }
  }

  /// 更新对象列表中的某个对象
  Future<bool> updateObjectInList(String key, String idField, String idValue, Map<String, dynamic> updatedData) async {
    _checkInitialized();
    try {
      final list = getObjectList(key);
      final index = list.indexWhere((item) => item[idField] == idValue);
      if (index >= 0) {
        list[index] = { ...list[index], ...updatedData };
        return await saveObjectList(key, list);
      }
      return false;
    } catch (e) {
      // 移除print语句，返回false表示操作失败
      return false;
    }
  }

  /// 从列表中删除对象
  Future<bool> removeObjectFromList(String key, String idField, String idValue) async {
    _checkInitialized();
    try {
      final list = getObjectList(key);
      final newList = list.where((item) => item[idField] != idValue).toList();
      return await saveObjectList(key, newList);
    } catch (e) {
      // 移除print语句，返回false表示操作失败
      return false;
    }
  }

  /// 删除对象列表中的指定项
  Future<bool> deleteObjectFromList(String key, String objectId) async {
    _checkInitialized();
    try {
      final list = getObjectList(key);
      final newList = list.where((item) => item['id'] != objectId).toList();
      return await saveObjectList(key, newList);
    } catch (e) {
      // 移除print语句，返回false表示操作失败
      return false;
    }
  }

  /// 添加对象到列表
  Future<bool> addObjectToList(String key, Map<String, dynamic> data) async {
    _checkInitialized();
    try {
      final list = getObjectList(key);
      list.add(data);
      return await saveObjectList(key, list);
    } catch (e) {
      // 移除print语句，返回false表示操作失败
      return false;
    }
  }

  /// 保存字符串
  Future<bool> saveString(String key, String value) async {
    _checkInitialized();
    return await _prefs.setString(key, value);
  }

  /// 获取字符串
  String? getString(String key) {
    _checkInitialized();
    return _prefs.getString(key);
  }

  /// 保存整数
  Future<bool> saveInt(String key, int value) async {
    _checkInitialized();
    return await _prefs.setInt(key, value);
  }

  /// 获取整数
  int? getInt(String key) {
    _checkInitialized();
    return _prefs.getInt(key);
  }

  /// 保存布尔值
  Future<bool> saveBool(String key, bool value) async {
    _checkInitialized();
    return await _prefs.setBool(key, value);
  }

  /// 获取布尔值
  bool? getBool(String key) {
    _checkInitialized();
    return _prefs.getBool(key);
  }

  /// 保存双精度浮点数
  Future<bool> saveDouble(String key, double value) async {
    _checkInitialized();
    return await _prefs.setDouble(key, value);
  }

  /// 获取双精度浮点数
  double? getDouble(String key) {
    _checkInitialized();
    return _prefs.getDouble(key);
  }

  /// 删除键
  Future<bool> remove(String key) async {
    _checkInitialized();
    try {
      return await _prefs.remove(key);
    } catch (e) {
      // 移除print语句，返回false表示操作失败
      return false;
    }
  }

  /// 清空所有数据
  Future<bool> clear() async {
    _checkInitialized();
    // 只清空我们的应用数据
    final keys = _prefs.getKeys().where((key) => key.startsWith(_prefix)).toList();
    for (final key in keys) {
      await _prefs.remove(key);
    }
    return true;
  }

  /// 获取所有键
  Set<String> getKeys() {
    _checkInitialized();
    return _prefs.getKeys().where((key) => key.startsWith(_prefix)).toSet();
  }

  /// 检查键是否存在
  bool containsKey(String key) {
    _checkInitialized();
    return _prefs.containsKey(key);
  }

  /// 保存字符串列表
  Future<bool> saveStringList(String key, List<String> value) async {
    _checkInitialized();
    return await _prefs.setStringList(key, value);
  }

  /// 获取字符串列表
  List<String>? getStringList(String key) {
    _checkInitialized();
    return _prefs.getStringList(key);
  }

  /// 按日期范围查询数据
  List<Map<String, dynamic>> queryByDateRange(String key, String dateField, DateTime startDate, DateTime endDate) {
    _checkInitialized();
    try {
      final list = getObjectList(key);
      final start = startDate.millisecondsSinceEpoch;
      final end = endDate.millisecondsSinceEpoch;
      
      return list.where((item) {
        if (item[dateField] is String) {
          final date = DateTime.parse(item[dateField]).millisecondsSinceEpoch;
          return date >= start && date <= end;
        } else if (item[dateField] is int) {
          return item[dateField] >= start && item[dateField] <= end;
        }
        return false;
      }).toList();
    } catch (e) {
      // 移除print语句，返回空列表表示查询失败
      return [];
    }
  }

  /// 根据用户ID查询数据
  List<Map<String, dynamic>> queryByUserId(String key, String userId) {
    _checkInitialized();
    try {
      final list = getObjectList(key);
      return list.where((item) => item['user_id'] == userId).toList();
    } catch (e) {
      // 移除print语句，返回空列表表示查询失败
      return [];
    }
  }
}